import csv

import requests
from lxml import etree


class SGuaZiCar:
    def __init__(self):

        self.list1 = list()
        self.head = ['车型', '发布日期', '里程数', '现价', '原价']

    def spider(self):
        for a in range(1, 11):
            url = "https://www.guazi.com/wh/buy/o%s/" % a
            headers = {
                "Host": "www.guazi.com",
                "Referer": "https://www.guazi.com/wh/buy/",
                "Cookie": "track_id=142542723226009600; uuid=22ba7c3f-1833-4a4a-f2bf-d7f5c7500553; antipas=7075450750G89844u919929g2; clueSourceCode=%2A%2300; Hm_lvt_bf3ee5b290ce731c7a4ce7a617256354=1605140036; ganji_uuid=8943631727001316854952; sessionid=0a023880-a811-4a94-f6b6-ecd4deed5215; lg=1; cainfo=%7B%22ca_a%22%3A%22-%22%2C%22ca_b%22%3A%22-%22%2C%22ca_s%22%3A%22pz_baidu%22%2C%22ca_n%22%3A%22pcbiaoti%22%2C%22ca_medium%22%3A%22-%22%2C%22ca_term%22%3A%22-%22%2C%22ca_content%22%3A%22%22%2C%22ca_campaign%22%3A%22%22%2C%22ca_kw%22%3A%22-%22%2C%22ca_i%22%3A%22-%22%2C%22scode%22%3A%22-%22%2C%22keyword%22%3A%22-%22%2C%22ca_keywordid%22%3A%22-%22%2C%22ca_transid%22%3A%22%22%2C%22platform%22%3A%221%22%2C%22version%22%3A1%2C%22track_id%22%3A%22142542723226009600%22%2C%22display_finance_flag%22%3A%22-%22%2C%22client_ab%22%3A%22-%22%2C%22guid%22%3A%2222ba7c3f-1833-4a4a-f2bf-d7f5c7500553%22%2C%22ca_city%22%3A%22nj%22%2C%22sessionid%22%3A%220a023880-a811-4a94-f6b6-ecd4deed5215%22%7D; close_finance_popup=2020-11-12; user_city_id=194; cityDomain=wh; preTime=%7B%22last%22%3A1605140317%2C%22this%22%3A1605140033%2C%22pre%22%3A1605140033%7D; Hm_lpvt_bf3ee5b290ce731c7a4ce7a617256354=1605140319",
                "Sec-Fetch-Mode": "navigate",
                "Sec-Fetch-Site": "same-origin",
                "Sec-Fetch-Use": "?1",
                "Upgrade-Insecure-Requests": "1",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36 SLBrowser/6.0.1.8131"
            }

            r = requests.get(url=url, headers=headers)
            # with open("test1.txt", "w", encoding="utf-8") as f:
            #     f.write(r.content.decode())
            html = etree.HTML(r.content.decode())
            title_list = html.xpath("//ul/li/a//h2/text()")
            # print(title_list)
            year_list = html.xpath('//ul/li/a//div[@class="t-i"]/text()')
            # print(year_list[::3])
            far_list = html.xpath('//ul/li/a//div[@class="t-i"]/text()')
            # print(far_list[1::3])
            new_list = html.xpath('//ul/li/a//div[@class="t-price"]/p/text()')
            # print(new_list[::2])
            old_price_list = html.xpath('//ul/li/a//div[@class="t-price"]/em/text()')
            # print(old_price_list)

            for i in range(len(title_list)):
                dict1 = dict()
                dict1['车型'] = title_list[i]
                dict1['发布日期'] = year_list[::3][i]
                dict1['里程数'] = far_list[1::3][i]
                dict1['现价'] = new_list[::2][i]
                dict1['原价'] = old_price_list[i]
                self.list1.append(dict1)

    def save_csv(self):
        with open('GuaZiCar.csv', 'w') as f:
            # 创建一个csv的DictWriter对象，这样才能够将写入csv格式数据到这个文件
            f_csv = csv.DictWriter(f, self.head)
            # 写入一行（我们用第一行当做表头）
            f_csv.writeheader()
            # 写入多行行（当做数据）
            f_csv.writerows(self.list1)


if __name__ == '__main__':
    scar = SGuaZiCar()
    scar.spider()
    scar.save_csv()
